<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
import { getExamPage, getQuestionsList, getQuestionsAdd, getQuestionsDel, getQuestionsEdit, importing } from "@/api/exam/index";
import { queryExam, PageList } from "@/api/exam/types";
import Editor from "@/components/WangEditor/index.vue";
import { UploadRawFile, UploadRequestOptions } from "element-plus";
import type { FormInstance, UploadInstance, UploadUserFile } from 'element-plus'
import { genFileId } from 'element-plus'

const queryFormRef = ref(ElForm); // 查询表单
const loading = ref(false);
const total = ref(0);
// 图片域名
const imgUrl = ref(import.meta.env.VITE_APP_BASE_API);

// 列表查询参数
const queryParams = reactive<queryExam>({
  page: 1,
  page_size: 10,
  stem: "",
  question_type: "",
  pid: ''
});

const tableList = ref<PageList[]>();

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getQuestionsList(queryParams).then(({ data }) => {
    tableList.value = data.data;
    total.value = data.total;
  })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 弹窗数据
const dialog = reactive({
  title: '新增',
  visible: false
});

// 表单校验
const rules = reactive({
  stem: [
    { required: true, message: '请输入題目', trigger: 'blur' }
  ],
  pid: [
    { required: true, message: '请选择分类', trigger: 'selection-changenge' }
  ],
  image: [
    { required: true, message: '请上传图片', trigger: 'blur' }
  ]
})

// 新增提交数据
const formData = reactive({
  id: 0,
  question_type: 1,
  pid: '',
  stem: '',
  image: '',
  option: [],
  answer: '',
  difficulty: 1,
  sort: 0,
  analysis: '',
  url: '',
  answerValue: [],
});


// 初始化选择
const choiceList = ref<any[]>([{ value: '' }, { value: '' }]);

const ruleFormRef = ref<FormInstance>();

// 打开弹窗
const hanldeOpenDialog = (data: any | null = null) => {
  dialog.visible = true;
  if (data) {
    dialog.title = '编辑';
    formData.id = data.id;
    formData.pid = data.pid;
    formData.stem = data.stem;
    formData.image = data.image;
    formData.option = data.option;
    formData.answer = data.answer;
    formData.difficulty = data.difficulty;
    formData.question_type = data.question_type;
    formData.sort = data.sort;
    formData.analysis = data.analysis;
    formData.url = imgUrl.value + data.image;
    choiceList.value = data.option.map((item: any) => { return { value: item } }) as any;
    formData.answerValue = data.answer.split(',') as any;
  } else {
    dialog.title = '新增';
    choiceList.value = [{ value: '' }, { value: '' }];
    formData.question_type = 1;
    formData.answerValue = [];
    formData.analysis = '';
    formData.difficulty = 1;
    formData.url = '';
    formData.sort = 0;
    formData.option = [];
    formData.answer = '';
    formData.url = '';
    formData.image = '';
    formData.pid = '';
  }
}


// 获取图片回显
const updatepostUrl = (url: string) => {
  formData.url = imgUrl.value + url;
  formData.image = url;
}

// 关闭弹窗
const closeDialog = () => {
  dialog.visible = false;

}

// 提交数据
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (formData.question_type == 2) {
    formData.answer = formData.answerValue.join(',');
  }
  formData.option = choiceList.value.map((item: any) => { return item.value }) as any;
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (dialog.title == '新增') {
        getQuestionsAdd(formData).then(res => {
          ElMessage.success('新增成功');
          handleQuery();
          closeDialog();
          formEl.resetFields();
        })
      }
      if (dialog.title == '编辑') {
        getQuestionsEdit(formData).then(res => {
          ElMessage.success('编辑成功');
          handleQuery();
          closeDialog();
          formEl.resetFields();
        })
      }
    }
  });
}

// 提前获取数据
const selectList = ref<any[]>([]);
const dataInfo = () => {
  // 获取顶级分类
  getExamPage({}).then(({ data }) => {
    selectList.value = data;
  })
}

// 新增选项
const addChoiceList = () => {
  if (choiceList.value.length >= 10) {
    ElMessage.warning('选项不能超过10个');
    return;
  }
  choiceList.value.push({ value: '' });
}

// 删除选项
const hanldeDelChoice = (index: number) => {
  choiceList.value.splice(index, 1);
}


// 删除列表
const handleDelete = async (id: number) => {
  await ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",

  }).then(async () => {
    let res = await getQuestionsDel({ id: id }) as any;
    ElMessage.success(res.msg);
    handleQuery();
  }).catch(() => {
    ElMessage({
      type: "info",
      message: "已取消删除",
    });
  });;
}

// 下载模版 
const handleDownload = () => {
  location.href = "http://api.huojisuan.com/static/template.xlsx";
}

let uploadDialog = reactive({
  visible: false,
})

// 导入
const handleImport = () => {
  uploadDialog.visible = true;
}

const fileList = ref<UploadUserFile[]>([])

const uploadRef = ref<UploadInstance>()

// 上传限制回调
const handleExceed = (files: any) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
  uploadRef.value!.submit()
}

// 关闭上传弹窗
const handleClose = () => {
  uploadDialog.visible = false;
  fileList.value = []
}

/**
 * 自定义上传
 *
 * @param options
 */
async function uploadFile(options: UploadRequestOptions): Promise<any> {
  let data = {
    file: options.file,
    type: 'file',
  }

  const res = await importing(data) as any;
  ElMessage.success(res.msg);
  handleQuery();

}

onMounted(() => {
  handleQuery(); // 初始化用户列表数据
  dataInfo(); // 获取课程分类
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="试题搜索" prop="stem">
              <el-input v-model="queryParams.stem" placeholder="输入素材名称" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="试题题型" prop="question_type">
              <el-select v-model="queryParams.question_type" placeholder="选择素材分类" clearable style="width: 200px"
                @change="handleQuery">
                <el-option label="全选" value="" />
                <el-option label="判断题" :value="3" />
                <el-option label="多选题" :value="2" />
                <el-option label="单选题" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="专题分类" prop="pid">
              <el-tree-select value-key="id" placeholder="请输入课程分类" style="width: 200px" v-model="queryParams.pid"
                :props="{ children: 'child', label: 'title' }" :data="selectList" check-strictly
                :render-after-expand="false">
              </el-tree-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button @click="hanldeOpenDialog()" type="success"><i-ep-plus />新增</el-button>
                <el-button @click="handleDownload" type="primary">下载模版</el-button>
                <el-button @click="handleImport" type="primary">导入试题</el-button>
              </div>
            </div>
          </template>
          <el-table v-loading="loading" :data="tableList">
            <el-table-column label="编号" align="center" prop="id" width="100" />
            <el-table-column label="分类" align="center" prop="cate_title" />
            <el-table-column label="题干" align="center" prop="analysis">
              <template #default="scope">
                <span v-html="scope.row.analysis"></span>
              </template>
            </el-table-column>
            <el-table-column label="提型" align="center" prop="question_type">
              <template #default="scope">
                <span v-if="scope.row.question_type == 1">单选题</span>
                <span v-if="scope.row.question_type == 2">多选题</span>
                <span v-if="scope.row.question_type == 3">判断题</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="add_time" />
            <el-table-column label="难度" align="center" prop="difficulty" />
            <el-table-column label="排序" align="center" prop="sort" />
            <el-table-column label="操作" fixed="right" align="center" width="280">
              <template #default="scope">
                <el-button @click="hanldeOpenDialog(scope.row)" type="primary" size="small"><i-ep-edit />编辑</el-button>
                <el-button @click="handleDelete(scope.row.id)" type="danger" size="small"><i-ep-delete />删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
            v-model:limit="queryParams.page_size" @pagination="handleQuery" />
        </el-card>
      </el-col>
    </el-row>


    <el-dialog v-model="dialog.visible" :title="dialog.title" width="60%" append-to-body @close="closeDialog">
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="题型" prop="name">
          <el-radio-group v-model="formData.question_type">
            <el-radio :value="1">单选题 </el-radio>
            <el-radio :value="2">多选题</el-radio>
            <el-radio :value="3">判断题</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="分类" prop="pid" style="height: 100%;">
          <el-tree-select value-key="id" placeholder="请输入课程分类" style="width: 200px" v-model="formData.pid"
            :props="{ children: 'child', label: 'title' }" :data="selectList" check-strictly
            :render-after-expand="false">
          </el-tree-select>
        </el-form-item>

        <el-form-item label="题目" prop="stem">
          <el-input v-model="formData.stem" placeholder="请输入题目" />
        </el-form-item>

        <el-form-item label="插图">
          <single-upload @updatepostUrl="updatepostUrl" v-model="formData.url" type="image" />
        </el-form-item>

        <el-form-item :label="String.fromCharCode(64 + (index + 1))" v-for="(item, index) in choiceList">
          <div class="flex" style="width: 100%;">
            <el-input clearable class="mr-10 flex-1" v-model="item.value" placeholder="请输入选项" />
            <div style="width: 100px;">
              <el-button @click="hanldeDelChoice(index)" v-if="index > 1" type="danger">删除选项</el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <div class="flex">
            <el-button type="primary" @click="addChoiceList">新增选项</el-button>
            <span>（最多添加10个选项）</span>
          </div>
        </el-form-item>

        <el-form-item label="正确答案" prop="answer">
          <el-checkbox-group v-if="formData.question_type == 2" v-model="formData.answerValue" size="small">
            <el-checkbox v-for="(item, index) in choiceList" :value="String.fromCharCode(64 + (index + 1))" border
              :label="String.fromCharCode(64 + (index + 1))" />
          </el-checkbox-group>
          <el-radio-group v-else v-model="formData.answer">
            <el-radio v-for="(item, index) in choiceList" :value="String.fromCharCode(64 + (index + 1))">
              {{ String.fromCharCode(64 + (index + 1)) }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="试题难度" prop="difficulty">
          <el-rate size="large" v-model="formData.difficulty" style="height: 30px;" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="答题解析" prop="analysis">
          <div style="border:1px solid #EBEEFF;height: 490px;">
            <editor v-model="formData.analysis" style="height: 400px; width: 100%;" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit(ruleFormRef)">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog v-model="uploadDialog.visible" title="导入试题" width="600px" :before-close="handleClose">
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="上传试题" prop="name">
          <el-upload ref="uploadRef" class="upload-demo" v-model:file-list="fileList" :http-request="uploadFile"
            :limit="1" :on-exceed="handleExceed">
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                上传模版试题
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
:deep() {

  .el-form-item__content,
  .upload-demo {
    width: 100%;
  }
}
</style>
